package LCR_code;

import Lee_code.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author blh
 * @date 2024年08月05日 9:10
 */
public class LCR_153_85 {
    List<List<Integer>> res = new ArrayList<>();
    int tar;

    public List<List<Integer>> pathTarget(TreeNode root, int target) {
        // 直接一个dfs
        tar = target;
        if (root == null) {
            return res;
        }
        ArrayList<Integer> temp = new ArrayList<>();
        temp.add(root.val);
        dfs(root, temp, root.val);
        return res;
    }

    private void dfs(TreeNode root, ArrayList<Integer> list, int sum) {
        if (root.right == null && root.left == null && sum == tar) {
            res.add(new ArrayList<>(list));
            return;
        }
        if (root.left != null) {
            sum = sum + root.left.val;
            list.add(root.left.val);
            dfs(root.left, list, sum);
            list.remove(list.size() - 1);
        }
        if (root.right != null) {
            sum = sum + root.right.val;
            list.add(root.right.val);
            dfs(root.right, list, sum);
            list.remove(list.size() - 1);
        }
    }
}
